package com.yu.dv.service;

import com.yu.dv.autoconfigure.properties.NaturalLanguageSqlProperties;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

public class InputValidator {

    private final NaturalLanguageSqlProperties properties;
    private static final String[] FORBIDDEN_KEYWORDS = {
            "drop database", "delete from", "truncate", "system", "exec"
    };

    public InputValidator(NaturalLanguageSqlProperties properties) {
        this.properties = properties;
    }

    public ValidationResult validate(String naturalLanguage) {
        if (StringUtils.isBlank(naturalLanguage)) {
            return ValidationResult.error("输入不能为空");
        }

        if (naturalLanguage.length() > properties.getMaxInputLength()) {
            return ValidationResult.error("输入长度不能超过" + properties.getMaxInputLength() + "个字符");
        }

        String lowerInput = naturalLanguage.toLowerCase();
        for (String keyword : FORBIDDEN_KEYWORDS) {
            if (lowerInput.contains(keyword)) {
                return ValidationResult.error("输入包含不允许的关键词: " + keyword);
            }
        }

        if (containsSqlInjectionPattern(naturalLanguage)) {
            return ValidationResult.error("输入包含可疑的SQL模式");
        }

        return ValidationResult.success();
    }

    private boolean containsSqlInjectionPattern(String input) {
        String[] patterns = {"--", ";", "\"", "'", "/*", "*/", "xp_", "sp_"};
        for (String pattern : patterns) {
            if (input.contains(pattern)) {
                return true;
            }
        }
        return false;
    }

    @Getter
    public static class ValidationResult {
        private final boolean valid;
        private final String errorMessage;

        private ValidationResult(boolean valid, String errorMessage) {
            this.valid = valid;
            this.errorMessage = errorMessage;
        }

        public static ValidationResult success() {
            return new ValidationResult(true, null);
        }

        public static ValidationResult error(String errorMessage) {
            return new ValidationResult(false, errorMessage);
        }
    }
}